今天要來介紹userDefault
這張圖我們可以看到userDefault儲存的類別~
要看更詳細的話,直接右鍵點userDefault,jump to definition就可以了~
接下來我們建立一個userDefault:
class UserPreference {
static let shared = UserPreference()
private let userPreference: UserDefaults
private init() {
userPreference = UserDefaults.standard
}
}
//設定要儲存的值(value)及key
userPreferences.set(你的值, forKey:你的值的key )
userPreference.型態(forKey: 你的值的 Key)
然後可以弄個enum讀key:
enum UserPreference: String {
case cat
case dog
case bird
}
整個弄好長這樣:
class GlobalAppSetting {
static let shared = GlobalAppSetting()
private let userPreferences: UserDefaults
private init() { userPreferences = UserDefaults.standard }
func resetUserDefault() {
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
}
enum UserPreference: String {
case dog
case bird
case cat
}
var dog: String {
get{ return userPreferences.string(forKey: UserPreference.dog.rawValue) ?? "" }
set{ userPreferences.set(newValue, forKey: UserPreference.dog.rawValue) }
}
var bird: String {
get{ return userPreferences.string(forKey: UserPreference.bird.rawValue) ?? "" }
set{ userPreferences.set(newValue, forKey: UserPreference.bird.rawValue) }
}
var cat: String {
get{ return userPreferences.string(forKey: UserPreference.cat.rawValue) ?? "" }
set{ userPreferences.set(newValue, forKey: UserPreference.cat.rawValue) }
}
}
GlobalAppSetting.shared.bird = "eagle"